package com.xuecheng.manage_cms_client.service;

import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.xuecheng.framework.domain.cms.CmsPage;
import com.xuecheng.framework.domain.cms.CmsSite;
import com.xuecheng.framework.domain.cms.response.CmsCode;
import com.xuecheng.framework.exception.CustomExcetionCast;
import com.xuecheng.manage_cms_client.dao.CmsPageRepository;
import com.xuecheng.manage_cms_client.dao.CmsSiteRepository;
import io.swagger.annotations.Api;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.*;
import java.util.Optional;

/**
 * @Description: 将生成的静态页面html保存到服务器路径
 * @Param:
 * @return:
 * @Author: Mr.Yuan
 * @Date:
 */
@Service
public class PageService {
    @Autowired
    GridFSBucket gridFSBucket;
    @Autowired
    GridFsTemplate gridFsTemplate;
    @Autowired
    CmsPageRepository cmsPageRepository;
    @Autowired
    CmsSiteRepository cmsSiteRepository;

    private static final Logger LOGGER = LoggerFactory.getLogger(PageService.class);

    //    将静态页面html保存到服务器路径
    public void savePageToServerPath(String pageId) {
        if(StringUtils.isEmpty(pageId)){
            LOGGER.error("PageService类中方法savePageToServerPath方法中，调用的页面id参数为空");
            throw CustomExcetionCast.getCusException(CmsCode.CMS_PGAEID_EMPTY);
        }
//        根据pageid找到页面相关信息
        Optional<CmsPage> cmsPageOptional = cmsPageRepository.findById(pageId);
        if (!cmsPageOptional.isPresent()) {
            throw CustomExcetionCast.getCusException(CmsCode.CMS_PGAE_NOEXIST);
        }
        CmsPage cmsPage = cmsPageOptional.get();
//        根据id查询页面是否存在
//        拿到站点id,htmlId
        String siteId = cmsPage.getSiteId();
//        获取页面的物理路径
        Optional<CmsSite> cmsSiteOptional = cmsSiteRepository.findById(siteId);
        if (!cmsPageOptional.isPresent()) {
            throw CustomExcetionCast.getCusException(CmsCode.CMS_PGAE_NOSITED);
        }
        CmsSite cmsSite = cmsSiteOptional.get();
        String sitePhysicalPath = cmsSite.getSitePhysicalPath();
//        得到页面的物理路径
//        String physPath = sitePhysicalPath + cmsPage.getPagePhysicalPath() + cmsPage.getPageName();
        String physPath =  cmsPage.getPagePhysicalPath() + cmsPage.getPageName();

        String htmlFileId = cmsPage.getHtmlFileId();
//        下载页面,根据htmlFileId
        InputStream fileInput = this.getFileById(htmlFileId);
        if (fileInput == null) {
            throw CustomExcetionCast.getCusException(CmsCode.CMS_GENERATEHTML_HTMLISNULL);
        }
        //        保存到服务器物理路径
        FileOutputStream fileOutputStream = null;
        try {
             fileOutputStream = new FileOutputStream(new File(physPath));
            IOUtils.copy(fileInput, fileOutputStream);
        } catch (IOException e) {
            throw CustomExcetionCast.getCusException(CmsCode.CMS_GENERATEHTML_SAVEHTMLERROR);
        }finally {
            try {
                fileInput.close();
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

    //获取文件输入流，从静态html数据库中
    private InputStream getFileById(String htmlFileId) {
        GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(htmlFileId)));
        if (StringUtils.isEmpty(gridFSFile)) {
            throw CustomExcetionCast.getCusException(CmsCode.CMS_GENERATEHTML_SAVEHTMLERROR);
        }
        GridFSDownloadStream stream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
        GridFsResource gridFsResource=new GridFsResource(gridFSFile,stream);
        InputStream inputStream = null;
        try {
            inputStream = gridFsResource.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return inputStream;
    }
}
